package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.model.WechatSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * 微信小程序工具类
 * 
 * @author ruoyi
 */
public class WechatUtils
{
    private static final Logger log = LoggerFactory.getLogger(WechatUtils.class);

    /**
     * 微信小程序登录接口URL
     */
    private static final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 获取微信小程序会话信息
     * 
     * @param appId 小程序AppId
     * @param appSecret 小程序AppSecret
     * @param code 登录凭证
     * @return 会话信息
     */
    public static WechatSession getWechatSession(String appId, String appSecret, String code)
    {
        try
        {
            RestTemplate restTemplate = new RestTemplate();
            String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    WECHAT_LOGIN_URL, appId, appSecret, code);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            HttpEntity<String> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            
            if (response.getStatusCode().is2xxSuccessful())
            {
                String responseBody = response.getBody();
                log.info("微信API响应: {}", responseBody);
                
                WechatSession session = JSON.parseObject(responseBody, WechatSession.class);
                return session;
            }
            else
            {
                log.error("微信API调用失败，状态码: {}", response.getStatusCode());
                return null;
            }
        }
        catch (Exception e)
        {
            log.error("获取微信会话信息失败", e);
            return null;
        }
    }

    /**
     * 验证微信会话是否有效
     * 
     * @param session 会话信息
     * @return 是否有效
     */
    public static boolean isValidSession(WechatSession session)
    {
        return session != null && 
               session.getErrcode() == null && 
               StringUtils.isNotEmpty(session.getOpenid());
    }
}
